package com.scau.clothes.config.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.scau.clothes.pojo.User;
import com.scau.clothes.service.UserService;
import com.scau.clothes.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;
import java.util.Enumeration;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    UserService userService;
    private static final String JWT_TOKEN = "JWT_TOKEN";
    private static final String USER_ID = "userId";
    private static final String USER_NAME = "username";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies == null||cookies.length==0){
        }else{
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName());
                if (cookie.getName().equals(JWT_TOKEN)) {
                    String token = cookie.getValue();
                    try{
                        DecodedJWT verify = JwtUtils.verify(token);
                        User user = new User();
                        user.setId(Integer.parseInt(verify.getClaim(USER_ID).asString()));
                        //检查是否在logout名单中
                        if(userService.isInLogoutList(user.getId())){
                            response.sendRedirect("/toLogin");
                            return false;
                        }
                        user.setUserName(verify.getClaim(USER_NAME).asString());
                        request.setAttribute("user",user);
                        return true;
                    }catch (SignatureVerificationException e){
                        e.printStackTrace();
                    }catch (TokenExpiredException e){
                        e.printStackTrace();
                    }catch (AlgorithmMismatchException e){
                        e.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        response.sendRedirect("/toLogin");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv) throws Exception {
        User user = (User) request.getAttribute("user");
        mv.addObject(USER_ID,user.getId()+"");
        mv.addObject(USER_NAME,user.getUserName());
    }
}
